package com.daodaofun.weibo.controller;

import com.daodaofun.util.CommonCode;
import com.daodaofun.util.PageInfo;
import com.daodaofun.weibo.dto.UserDto;
import com.daodaofun.weibo.model.Post;
import com.daodaofun.weibo.model.PostInfo;
import com.daodaofun.weibo.model.User;
import com.daodaofun.weibo.service.PostService;
import com.daodaofun.weibo.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * 用户控制器
 */
@Controller
@RequestMapping("u")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PostService postService;

    /**
     * 跳转注册页面
     * @return
     */
    @RequestMapping("to/register")
    public String toRegister(){

        return "user/register";
    }

    /**
     * 跳转登录页面
     * @return
     */
    @RequestMapping("to/login")
    public String toLogin(){

        return "user/login";
    }


    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public String register(User user){
        userService.save(user);
        return "user/login";
    }

    /**
     * 登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("login")
    public String login(User user, HttpSession session, Model model){
       User u =  userService.findByUsername(user.getUsername());
       if(u == null){
           // 用户名错误，不存在用户
           return "user/login";
       } else {
           if(user.getPassword().equals(u.getPassword())) {
               // 登陆成功

               // 查询就近时间的微博
               List<PostInfo> posts = postService.listCurrentPosts(u.getId());
               model.addAttribute("posts",posts);
               // 查询一下关注数量
               long followCount =  userService.countFollows(u.getId());
               u.setTotalFocus(followCount);
               long fansCount = userService.countFans(u.getId());
               u.setTotalFans(fansCount);
               session.setAttribute("user",u);
               return "home";
           } else {
               // 密码错误
               return "user/login";
           }
       }
    }

    @RequestMapping("search/{content}")
    public String search(@PathVariable("content") String content,Model model,HttpSession session){
        User user = (User) session.getAttribute("user");
        Long userId = user.getId();
        Set<String> follows = userService.findFollows(userId);
        content = content.trim();
        List<UserDto> users = userService.findByUsernameLike(content);
//        model.addAttribute("users",users);
        List<UserDto> userDtos = handleFollowsUsers(follows,users);
        model.addAttribute("users",userDtos);
        return "user/nicknameSearchResult";
    }


    /**
     * 关注与取关
     * @param of
     * @param startId
     * @param session
     * @return
     */
    @RequestMapping("star/{of}/{startId}")
    @ResponseBody
    public Integer star(@PathVariable("of") Integer of,@PathVariable("startId") Long startId,HttpSession session){
        User user = (User) session.getAttribute("user");
        userService.starOnOrOff(of,user.getId(),startId);
        return CommonCode.SUCCESS;
    }



    private List<UserDto> handleFollowsUsers(Set<String> follows, List<UserDto> users) {
//        List<UserDto> userDtos = new ArrayList<>();
        
        

        for(int i = 0 ; i < users.size();i++){
            Long id = users.get(i).getId();
            Iterator<String> it = follows.iterator();
            while(it.hasNext()){
                String next = it.next();
                if(next.equals(id+"")){
                    users.get(i).setOn(true);
                    break;
                }
            }
        }
        return users;
    }


    /**
     * 查询某个用户的所有关注的人
     * @param  id 当前主动关注者的id
     * @return
     */
    @RequestMapping("follows/{id}")
    public String findFollows(@PathVariable("id") Long id,Model model){
        List<UserDto> follows = userService.findFollowsUser(id);
        model.addAttribute("follows",follows);
        return "user/follows";
    }
    /**
     * 查询某个用户的所有粉丝
     * @param  id 当前主动关注者的id
     * @return
     */
    @RequestMapping("fans/{id}/{pageNum}")
    @ResponseBody
    public PageInfo<UserDto> findFans(@PathVariable("id") Long id  ,@PathVariable("pageNum") Integer pageNum){
        PageInfo<UserDto> page = userService.findFansUser(id,pageNum);
        return  page;
    }
    @RequestMapping("fans")
    public String fans(){
//        List<UserDto> fans = userService.findFansUser(id);
//        model.addAttribute("fans",fans);
        return "user/fans";
    }
}













